package com.hbnu.controller;

import com.hbnu.pojo.ApiResult;
import com.hbnu.pojo.Room;
import com.hbnu.pojo.RoomMember;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbnu.mapper.RoomMapper;
import com.hbnu.mapper.RoomMemberMapper;
import com.hbnu.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/room")
@CrossOrigin(origins = "*")
public class RoomController {

    @Autowired
    private RoomService roomService;
    
    @Autowired
    private RoomMapper roomMapper;
    
    @Autowired
    private RoomMemberMapper roomMemberMapper;

    /**
     * 创建房间
     */
    @PostMapping("/create")
    public Map<String, Object> createRoom(@RequestBody Map<String, String> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            String roomName = request.get("roomName");
            String creatorId = request.get("creatorId");
            
            if (roomName == null || roomName.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "房间名不能为空");
                return result;
            }
            
            if (creatorId == null || creatorId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "用户ID不能为空");
                return result;
            }
            
            Room room = roomService.createRoom(roomName, creatorId);
            result.put("success", true);
            result.put("message", "房间创建成功");
            result.put("roomId", room.getRoomId());
            result.put("roomName", room.getRoomName());
            result.put("room", room);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "创建房间失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 加入房间
     */
    @PostMapping("/join")
    public Map<String, Object> joinRoom(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer roomId = (Integer) request.get("roomId");
            String userId = (String) request.get("userId");
            
            if (roomId == null) {
                result.put("success", false);
                result.put("message", "房间ID不能为空");
                return result;
            }
            
            if (userId == null || userId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "用户ID不能为空");
                return result;
            }
            
            // 检查房间是否存在
            Room room = roomMapper.selectById(roomId);
            if (room == null) {
                result.put("success", false);
                result.put("message", "房间不存在");
                return result;
            }
            
            // 检查用户是否已在房间中
            QueryWrapper<RoomMember> wrapper = new QueryWrapper<>();
            wrapper.eq("room_id", roomId).eq("user_id", userId);
            RoomMember existingMember = roomMemberMapper.selectOne(wrapper);
            if (existingMember != null) {
                result.put("success", false);
                result.put("message", "您已在该房间中");
                return result;
            }
            
            boolean joined = roomService.joinRoom(roomId, userId);
            if (joined) {
                result.put("success", true);
                result.put("message", "成功加入房间");
                result.put("room", room);
            } else {
                result.put("success", false);
                result.put("message", "房间已满，无法加入");
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "加入房间失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 获取房间列表
     */
    @GetMapping("/list")
    public Map<String, Object> getRoomList() {
        Map<String, Object> result = new HashMap<>();
        try {
            QueryWrapper<Room> wrapper = new QueryWrapper<>();
            wrapper.eq("status", "waiting").orderByDesc("created_time");
            List<Room> rooms = roomMapper.selectList(wrapper);
            
            result.put("success", true);
            result.put("message", "获取房间列表成功");
            result.put("rooms", rooms);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取房间列表失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 获取房间详情
     */
    @GetMapping("/detail/{roomId}")
    public Map<String, Object> getRoomDetail(@PathVariable Integer roomId) {
        Map<String, Object> result = new HashMap<>();
        try {
            Room room = roomMapper.selectById(roomId);
//            if (room == null) {
//                result.put("success", false);
//                result.put("message", "房间不存在");
//                return result;
//            }
            
            // 获取房间成员
            QueryWrapper<RoomMember> wrapper = new QueryWrapper<>();
            wrapper.eq("room_id", roomId);
            List<RoomMember> members = roomMemberMapper.selectList(wrapper);
            
            result.put("success", true);
            result.put("message", "获取房间详情成功");
            result.put("room", room);
            result.put("members", members);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取房间详情失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 设置准备状态
     */
    @PostMapping("/ready")
    public Map<String, Object> setReady(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer roomId = (Integer) request.get("roomId");
            String userId = (String) request.get("userId");
            
            if (roomId == null || userId == null) {
                result.put("success", false);
                result.put("message", "参数不能为空");
                return result;
            }
            
            boolean ready = roomService.setReady(roomId, userId);
            if (ready) {
                result.put("success", true);
                result.put("message", "设置准备状态成功");
                
                // 检查是否可以开始游戏
                boolean canStart = roomService.canStartGame(roomId);
                result.put("canStartGame", canStart);
            } else {
                result.put("success", false);
                result.put("message", "设置准备状态失败");
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "设置准备状态失败: " + e.getMessage());
        }
        return result;
    }

    @PostMapping("/leave")
    public ApiResult leaveRoom(@RequestBody Map<String, Object> req) {
        Integer roomId = Integer.valueOf(req.get("roomId").toString());
        String userId = req.get("userId").toString();

        boolean success = roomService.leaveRoom(roomId, userId);
        return success ? ApiResult.success("已离开房间") : ApiResult.error("离开失败");
    }

    /**
     * 离开房间
     */
//    @PostMapping("/leave")
//    public Map<String, Object> leaveRoom(@RequestBody Map<String, Object> request) {
//        Map<String, Object> result = new HashMap<>();
//        try {
//            Integer roomId = (Integer) request.get("roomId");
//            String userId = (String) request.get("userId");
//
//            if (roomId == null || userId == null) {
//                result.put("success", false);
//                result.put("message", "参数不能为空");
//                return result;
//            }
//
//            // 删除房间成员记录
//            QueryWrapper<RoomMember> wrapper = new QueryWrapper<>();
//            wrapper.eq("room_id", roomId).eq("user_id", userId);
//            int deleted = roomMemberMapper.delete(wrapper);
//
//            if (deleted > 0) {
//                // 更新房间当前人数
//                Room room = roomMapper.selectById(roomId);
//                if (room != null) {
//                    room.setCurrentPlayers(room.getCurrentPlayers() - 1);
//                    roomMapper.updateById(room);
//                }
//
//                result.put("success", true);
//                result.put("message", "成功离开房间");
//            } else {
//                result.put("success", false);
//                result.put("message", "您不在该房间中");
//            }
//
//        } catch (Exception e) {
//            result.put("success", false);
//            result.put("message", "离开房间失败: " + e.getMessage());
//        }
//        return result;
//    }
}